package com.easydev.faseboot.taskfilter.starter;

import com.easydev.faseboot.taskfilter.annotation.TaskFilters;
import com.easydev.faseboot.taskfilter.filter.TaskFilter;
import com.easydev.faseboot.taskfilter.task.Task;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Arrays;

public class TaskFilterStarter implements BeanPostProcessor, ApplicationContextAware {
    private ApplicationContext applicationContext;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return null;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof Task) {
            Class<?> aClass = bean.getClass();
            if (!aClass.isAnnotationPresent(TaskFilters.class)) {
                return bean;
            }
            Task task = (Task) bean;

            TaskFilters taskFilters = aClass.getAnnotation(TaskFilters.class);
            String value = taskFilters.value();
            if (value == null || value.isEmpty()) {
                return bean;
            }

            String[] filterNames = value.split(",");

            Arrays.stream(filterNames).forEach(s -> {
                if (s != null && !s.isEmpty()) {
                    TaskFilter taskFilter = applicationContext.getBean(s, TaskFilter.class);
                    if (taskFilter != null) {
                        task.add(taskFilter);

                    }
                }
            });

        }
        return bean;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
